-module(element_users).
-compile(export_all).

-include_lib("nitrogen/include/wf.inc").
-include("elements.hrl").

wire(IDs) ->
    wf:wire(element(5, IDs), element(1, IDs), #validate {
			validators=[
				    #is_required { text = "X" }
				   ] }),
    wf:wire(element(5, IDs), element(2, IDs), #validate {
			validators=[
				    #is_required { text="X" },
				    #min_length { length=5, text=">5" }
				   ] }),
    wf:wire(element(5, IDs), element(3, IDs), #validate {
			validators=[
				    #is_required { text="X" },
				    #confirm_password { password=element(2, IDs),  text="X" }
				   ] }),
    wf:wire(element(5, IDs), element(4, IDs), #validate { 
			validators=[
				    #is_required { text="X" },
				    #is_email { text="X" }
				   ]}),
    ok.

make_login(link, _) ->
    LinkID = wf:temp_id(),
    { {LinkID} , [#link{id = LinkID, text = "Se connecter"}] };

make_login(body, ControlID) ->
    NickBoxID = wf:temp_id(),
    PassBoxID = wf:temp_id(),
    KeepAliveID = wf:temp_id(),
    BtnID = ControlID,

    A = [
	 #p{},
	 #label{ text="Nom d'utilisateur : " },
	 #textbox{ id=NickBoxID, style="width:100%;" },

	 #p{},
	 #label{ text="Mot de passe : " },
	 #password{ id=PassBoxID, style="width: 100%;" },

	 #p{},
	 #checkbox { id=KeepAliveID, text="Rester connecter?", checked=true },

	 #p{},
	 #button{ id=BtnID, text="Connexion" }
	],

    { {NickBoxID, PassBoxID, KeepAliveID, BtnID} , A}.

make_register(link, _) ->
    LinkID = wf:temp_id(),
    { {LinkID} , [#link{id = LinkID, text = "S'inscrire"}] };

make_register(body, ControlID) ->
    NickBoxID = wf:temp_id(),
    PassBoxID = wf:temp_id(),
    ConfirmID = wf:temp_id(),
    EmailBoxID = wf:temp_id(),
    BtnID = ControlID,

    B = [ 
	  #p{},
	  #label{ text="Nom d'utilisateur : " },
	  #textbox{ id=NickBoxID },

	  #p{},
	  #label{ text="Mot de passe : " },
	  #password{ id=PassBoxID },

	  #p{},
	  #label{ text="Vérification : " },
	  #password{ id=ConfirmID },

	  #p{},
	  #label{ text="Email : " },
	  #textbox{ id=EmailBoxID },

	  #p{},
	  #button{ id=BtnID, text="S'inscrire !" }
	 ],
    { {NickBoxID, PassBoxID, ConfirmID, EmailBoxID, BtnID} , B}.


render(_, R) ->
    profile(login, R).

profile(P, R) ->
    ContainerID = wf:temp_id(),

    {LState, RState} = case P of
			   login ->
			       {body, link};
			   register ->
			       {link, body}
		       end,
    
    EvR = R#users.callback,
    Delegate = get_delegate( EvR ),
    Postback = get_postback( EvR ),
    
    {LCtrlID, LRender} = case R#users.login_id of
			     undefined ->
				 {undefined, false};
			     LID -> 
				 {LID, R#users.login}
			 end,

    {RCtrlID, RRender} = case R#users.register_id of
			     undefined ->
				 {undefined, false};
			     RID -> 
				 {RID, R#users.register}
			 end,

  %  {L_NickBoxID, L_PassBoxID, L_KeepAliveID, L_BtnID, A} = 
    { L_IDs, A } = 
	case LRender of
	    true -> make_login(LState, LCtrlID);
	    _ -> {undefined, undefined, undefined, undefined, []}
	end,

   % {LinkID, B} = 
    { R_IDs, B} = 
	case RRender of
	    true -> make_register(RState, RCtrlID);
	    _ -> {undefined, []}
	end,

    Users = A ++ [#p{} | B],

    Container = #panel{ id=ContainerID, body = Users, class = R#users.class },

    case RState of
	body ->
	    wire(R_IDs);
	_ ->
	    ok
    end,

    LWireID = case LState of 
		  link -> element(1, L_IDs);
		  _ -> element(4, L_IDs)
	      end, 
    RWireID = case RState of 
		  link -> element(1, R_IDs);
		  _ -> element(4, R_IDs)
	      end, 

    wf:wire(LWireID, #event{delegate=?MODULE, type=click, postback= {login, L_IDs, ContainerID, R, LState}}),
    wf:wire(LWireID, #event{delegate=Delegate, type=click, postback= {Postback, {L_IDs, ContainerID, LState} }}),

    wf:wire(RWireID, #event{delegate=?MODULE, type=click, postback= {register, R_IDs, ContainerID, R, RState}}),
    wf:wire(RWireID, #event{delegate=Delegate, type=click, postback= {Postback,{ R_IDs, ContainerID, RState} }}),

    element_panel:render(wf:temp_id(), Container).

event( {login, IDs, PanelID, R, LState} ) ->
    io:format("called with LState ~w ~n", [LState]),
    case LState of
	body ->
	    case users:login( wf:q(element(1, IDs)), wf:q(element(2,IDs)), wf:q(element(3,IDs)) ) of
		ok ->
		    wf:redirect("/web/index");
		wrong_info ->
		    wf:flash("Mauvais nom d'utilisateur / mot de passe")
	    end;
	link ->
	    io:format("called and gonna put this : ~p~n ", [profile(login, R)]),
	    wf:update(PanelID, profile( register, R ))
    end;
event( {register, IDs, PanelID, R, RState} ) ->
    case RState of
	body ->
	    case users:register( wf:q(element(1, IDs)), wf:q(element(2,IDs)), wf:q(element(4,IDs))) of
		ok ->
		    wf:redirect("/web/redirect");
		bad_nick ->
		    wf:flash("Ce nom d'utilisateur est déjà pris");
		unknown ->
		    wf:flash("Erreur inconnue");
		Reason ->
		    wf:flash("Erreur : " ++ Reason)
	    end;
	link ->
	    wf:update(PanelID, profile( register, R ))
    end;
event( {logout} ) ->
    users:logout(),
    wf:redirect("/web/index").
